package com.webAutoTest.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/11/12
 * \* Time: 13:51
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class commonDriver {
    //创建驱动对象并返回
    private static ChromeDriver driver;
    public static ChromeDriver getDriver(){
        if(driver == null){
            driver = new ChromeDriver();
            //添加隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        }
        return driver;
    }

    public List<String> getTime(){
        //文件名格式20220801-111111-毫秒
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        //文件夹名称格式2022-11-12
        SimpleDateFormat sim2 = new SimpleDateFormat("yyyy-MM-dd");
        String filename = sim1.format(System.currentTimeMillis());
        String dirname = sim2.format(System.currentTimeMillis());
        List<String> list = new ArrayList<>();
        list.add(dirname);
        list.add(filename);
        return list;
    }
    /**
     * 获取屏幕截图
     * str：类名下的用例
     */
    public void getScreenshot(String str) throws IOException {
        List<String> times = getTime();
        //生成的文件夹路径./src/test/autotest-2022-11-12/goodsbroser-20221112-214130.png
        String filename ="./src/test/autotest-"+times.get(0)+"/"+str+"-"+times.get(1)+".png";
        File srcfile = driver.getScreenshotAs(OutputType.FILE);
        //把屏幕截图放到指定的路径下
        FileUtils.copyFile(srcfile,new File(filename));
    }
}
